﻿namespace EggOfPanKu.Library.Objects
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Collections.ObjectModel;

    public class Deck
    {
        #region Fields

        private ObservableCollection<Card> _cards = new ObservableCollection<Card>();
        private bool _hasBeenModified = false;

        #endregion Fields

        #region Constructors

        public Deck(CardDeck DeckType)
        {
        }

        public Deck(IEnumerable<Card> CardList, CardDeck DeckType)
        {
            foreach (Card c in CardList)
            {
                Cards.Add(c);
            }
        }

        #endregion Constructors

        #region Properties

        public ObservableCollection<Card> Cards
        {
            get
            {
                return _cards;
            }
        }

        public bool HasBeenModified
        {
            get
            {
                return _hasBeenModified;
            }
            set
            {
                _hasBeenModified = value;
            }
        }

        #endregion Properties

        #region Methods

        public List<Card> DrawCards(int numberOfCards)
        {
            //Only possible to draw cards, if there are cards to draw
            if (numberOfCards > Cards.Count)
            {
                numberOfCards = Cards.Count;
            }

            List<Card> topCards = new List<Card>(numberOfCards);
            while (numberOfCards > 0)
            {
                topCards.Add(Cards[0]);
                Cards.RemoveAt(0);
                numberOfCards--;
            }

            return topCards;
        }

        public int GetCardCount(Card searchCard)
        {
            int count = 0;
            foreach (Card card in Cards)
            {
                if (card.CardID == searchCard.CardID)
                {
                    count++;
                }
            }

            return count;
        }

        public void ShuffleCards()
        {
            //Generate a randome number using a strong random number generator
            RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
            //Order the Card List using the random number
            _cards = (ObservableCollection<Card>)_cards.OrderBy(x => GetNextInt32(rnd));
        }

        //Static method used to sort the Card list
        private static int GetNextInt32(RNGCryptoServiceProvider rnd)
        {
            byte[] randomInt = new byte[4];
            rnd.GetBytes(randomInt);
            return Convert.ToInt32(randomInt[0]);
        }

        #endregion Methods
    }
}